package com.cnctema.easecalendar_weekly_view.activities

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.cnctema.easecalendar_weekly_view.database.Event
import com.cnctema.easecalendar_weekly_view.database.EventDatabaseDao
import com.cnctema.easecalendar_weekly_view.utils.FormatterUtils
import kotlinx.coroutines.*
import org.joda.time.DateTime

/**
 * @ClassName: AddEventViewModel
 * @Description: 添加日程类的ViewModel(类的作用描述)
 * @Author: cnctema
 * @CreateDate: 2020/5/27 11:24
 */
class AddEventViewModel(val app:Application,val database: EventDatabaseDao) :AndroidViewModel(app) {
    private val viewModelJob = Job()
    private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)

    lateinit var currEvent: Event   //当前日程
    var isNewEvent = true           //是否是新日程

    //初始化日程数据
    fun initializeCurrEvent(eventId: Long, weekTimestamp: Long, invitor: String,
                            callback: (event: Event) -> Unit) {
        uiScope.launch {
            var event = getEventFromDatabase(eventId, database)
            if (event != null) {
                currEvent = event
                isNewEvent = false
            } else {
                event = getNewEvent(weekTimestamp, invitor)
                currEvent = event
                isNewEvent = true
            }
            callback.invoke(event)
        }
    }

    // 获取日程数据
    private suspend fun getEventFromDatabase(eventId: Long, database: EventDatabaseDao): Event? {
        return withContext(Dispatchers.IO) {
            val event = database.get(eventId)
            event
        }
    }

    // 创建新的日程
    fun getNewEvent(weekTimestamp: Long, invitor: String): Event {
        return if (weekTimestamp == -1L) {
            Event(eventInvitor = invitor)
        } else {
            Event(
                startTimeMilli = FormatterUtils.getDateTimeFromTS(weekTimestamp).millis,
                endTimeMilli = FormatterUtils.getDateTimeFromTS(weekTimestamp)
                    .plusMinutes(30).millis,
                eventInvitor = invitor
            )
        }
    }

    // 重新计算开始或结束日期
    fun resetDate(year: Int, monthOfYear: Int, dayOfMonth: Int, sd: Int,
                  callback: (stDateTime: DateTime, edDateTime: DateTime,isReseted:Boolean) -> Unit) {
        var stDateTime = DateTime(currEvent.startTimeMilli)
        var edDateTime = DateTime(currEvent.endTimeMilli)
        var isRested = false
        when (sd) {
            0 -> {
                stDateTime = DateTime(year, monthOfYear, dayOfMonth,
                    stDateTime.hourOfDay, stDateTime.minuteOfHour, stDateTime.secondOfMinute
                )
                currEvent.startTimeMilli = stDateTime.millis
                if (stDateTime.millis > edDateTime.millis) {
                    edDateTime = stDateTime.plusMinutes(30)
                    currEvent.endTimeMilli = edDateTime.millis
                    isRested = true
                }
            }
            else -> {
                edDateTime = DateTime(year, monthOfYear, dayOfMonth,
                    edDateTime.hourOfDay, edDateTime.minuteOfHour, edDateTime.secondOfMinute
                )
                currEvent.endTimeMilli = edDateTime.millis
                if (stDateTime.millis > edDateTime.millis) {
                    stDateTime = edDateTime.minusMinutes(30)
                    currEvent.startTimeMilli = stDateTime.millis
                    isRested = true
                }
            }
        }
        callback.invoke(stDateTime, edDateTime,isRested)
    }

    // 重新计算开始或结束时间
    fun resetTime(hourOfDay: Int, minute: Int, sd: Int,
                  callback: (stDateTime: DateTime, edDateTime: DateTime,isReseted:Boolean) -> Unit) {
        var stDateTime = DateTime(currEvent.startTimeMilli)
        var edDateTime = DateTime(currEvent.endTimeMilli)
        var isRested = false
        when (sd) {
            0 -> {
                stDateTime = DateTime(stDateTime.year, stDateTime.monthOfYear, stDateTime.dayOfMonth,
                    hourOfDay, minute, stDateTime.secondOfMinute
                )
                currEvent.startTimeMilli = stDateTime.millis
                if (stDateTime.millis > edDateTime.millis) {
                    edDateTime = stDateTime.plusMinutes(30)
                    currEvent.endTimeMilli = edDateTime.millis
                    isRested = true
                }
            }
            else -> {
                edDateTime = DateTime(edDateTime.year, edDateTime.monthOfYear, edDateTime.dayOfMonth,
                    hourOfDay, minute, stDateTime.secondOfMinute
                )
                currEvent.endTimeMilli = edDateTime.millis
                if (stDateTime.millis > edDateTime.millis) {
                    stDateTime = edDateTime.minusMinutes(30)
                    currEvent.startTimeMilli = stDateTime.millis
                    isRested = true
                }
            }
        }
        callback.invoke(stDateTime, edDateTime,isRested)
    }

    // 保存日程
    fun saveCurrEvent(callback: (missType: Int) -> Unit) {
        if (currEvent.eventTitle == "") {
            callback(1)
            return
        }
        uiScope.launch {
            if(isNewEvent){
                insert(currEvent)   //插入新日程
            }else{
                update(currEvent)   //更新日程
            }
        }
        callback(0)
    }

    // 删除日程 --通过id
    fun deleteEventById(id:Long,callback:()->Unit){
        if(isNewEvent){return}
        uiScope.launch {
            deleteById(id)
            callback.invoke()
        }
    }

    //插入操作
    private suspend fun insert(event: Event){
        withContext(Dispatchers.IO) {
            database.insert(event)
        }
    }
    //更新操作
    private suspend fun update(event: Event){
        withContext(Dispatchers.IO) {
            database.update(event)
        }
    }
    //删除操作 --通过id
    private suspend fun deleteById(id: Long){
        withContext(Dispatchers.IO) {
            database.deleteById(id)
        }
    }

}
